<?php
class menu{
	// Menu builder function, parentId 0 is the root
	function buildMenu($parent, $menu)
		{
		$html = "";
		if (isset($menu['parents'][$parent]))
		{
		$html .= "<ul>";
		foreach ($menu['parents'][$parent] as $itemId)
		{
		if(!isset($menu['parents'][$itemId]))
		{
			if($menu['items'][$itemId]['link']=="")
			{
				$html .= "<li><a href='javascript:void(0);'>".$menu['items'][$itemId]['label']."</a></li>";
			}
			elseif($menu['items'][$itemId]['link']=="#")
			{
				$html .= "<li><a href='".$menu['items'][$itemId]['link']."'>".$menu['items'][$itemId]['label']."</a></li>";
			}
			else
			{
				$html .= "<li><a href='".$menu['items'][$itemId]['link']."'>".$menu['items'][$itemId]['label']."</a></li>";
			}
		}
		if(isset($menu['parents'][$itemId]))
		{
			if($menu['items'][$itemId]['link']=="")
			{
				$html .= "<li><a href='javascript:void(0);'>".$menu['items'][$itemId]['label']."</a>";
			}
			elseif($menu['items'][$itemId]['link']=="#")
			{
				$html .= "<li><a href='".$menu['items'][$itemId]['link']."'>".$menu['items'][$itemId]['label']."</a> ";
			}
			else
			{
				$html .= "<li><a href='".$menu['items'][$itemId]['link']."'>".$menu['items'][$itemId]['label']."</a>";
			}
		//$html .= "<li><a href='".$menu['items'][$itemId]['link']."'>".$menu['items'][$itemId]['label']."</a> ";
		$html .= $this->buildMenu($itemId, $menu);
		$html .= "</li> ";
		}
		}
		$html .= "</ul> ";
		}
		return $html;
		}
	function menu($parent=NULL)
	{
		$sql=new sql();
		$sql->connect();
                if($parent)
                {
                    $result=mysql_query("SELECT uid, label, link, parent FROM ".PREFIX."menu where parent=0 ORDER BY sort asc");
                }
                else
                {
                    $result=mysql_query("SELECT uid, label, link, parent FROM ".PREFIX."menu ORDER BY sort asc");
                }
		
		$menu = array(
		'items' => array(),
		'parents' => array()
		);
	  
		while ($items = mysql_fetch_assoc($result))
		{
		$menu['items'][$items['uid']] = magicKeyword($items);
		$menu['parents'][$items['parent']][] = $items['uid'];
		}

			$data= $this->buildMenu(0, $menu);
			return $data;
	}
}